package cs2340.flyingkiwi.todoapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;

/**
 * This class provides an access to the SQLite database for categories.
 * 
 * @author Group Flying Kiwi
 * @version 30 Mar 2012
 * 
 * It provides several key operations to communicate with the database.
 */

public class ToDoAppDbAdapter {
	public static final String KEY_ACCOUNT_USERNAME = "account_username";
	public static final String KEY_ACCOUNT_PASSWORD = "account_password";
	public static final String KEY_ACCOUNT_NAME = "account_name";
	public static final String KEY_ACCOUNT_EMAIL = "account_email";
	public static final String KEY_ACCOUNT_ROWID = "_id";
	
	public static final String KEY_CATEGORY_TITLE = "category_title";
	public static final String KEY_CATEGORY_ROWID = "_id";
	public static final String KEY_CATEGORY_ACCOUNTID = "account_id";
	
	public static final String KEY_ITEM_TITLE = "item_title";
	public static final String KEY_ITEM_DESCRIPTION = "item_description";
	public static final String KEY_ITEM_LOCATION = "item_location";
	public static final String KEY_ITEM_DUEDATE = "item_duedate";
	public static final String KEY_ITEM_COMPLETE = "item_complete";
	public static final String KEY_ITEM_ROWID = "_id";
	public static final String KEY_ITEM_ACCOUNTID = "account_id";
	public static final String KEY_ITEM_CATEGORYID = "category_id";
	
	
	private static final String TAG = "ToDoAppDbAdapter";
	private DbHelper mDbHelper;
	
	private SQLiteDatabase mMainDb;
	
	private static final String DATABASE_ACCOUNT_CREATE = 
			"create table account_table (_id integer primary key autoincrement, " +
			"account_username text not null, account_password text not null, " + 
			"account_name text not null, account_email text not null);";
	
	private static final String DATABASE_CATEGORY_CREATE = 
			"create table category_table (_id integer primary key autoincrement, " +
			"category_title text not null, account_id text not null);";
	
	private static final String DATABASE_ITEM_CREATE = 
			"create table item_table (_id integer primary key autoincrement, " +
			"item_title text not null, item_description text not null, " + 
			"item_location text not null, item_duedate text not null, " +
			"item_complete text not null, account_id text not null, " +
			"category_id text not null);";
	
	private static final String DATABASE_ACCOUNT_TABLE = "account_table";
	private static final String DATABASE_CATEGORY_TABLE = "category_table";
	private static final String DATABASE_ITEM_TABLE = "item_table";
	
	private static final String DATABASE_NAME = "data";
	
	private static final int DATABASE_VERSION = 8;
	
	private final Context mCtx;
	
	/**
	 * This private inner class actually makes the database and table
	 * by executing raw query.
	 */
	private static class DbHelper extends SQLiteOpenHelper {
		DbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        	db.execSQL(DATABASE_ACCOUNT_CREATE);
            db.execSQL(DATABASE_CATEGORY_CREATE);
            db.execSQL(DATABASE_ITEM_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS account_table");
            db.execSQL("DROP TABLE IF EXISTS category_table");
            db.execSQL("DROP TABLE IF EXISTS item_table");
            onCreate(db);
        }
	}
	
	
	/**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
	public ToDoAppDbAdapter(Context ctx){
		this.mCtx = ctx;
	}
	
	/**
     * Open the category database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
	public ToDoAppDbAdapter open() throws SQLException {
        mDbHelper = new DbHelper(mCtx);
        mMainDb = mDbHelper.getWritableDatabase();
       return this;
    }

	/**
	 * Close any open database object.
	 */
    public void close() {
        mDbHelper.close();
       
    }
    
    /**
     * Create a new account using the data provided. If the account is
     * successfully created return the new rowId for that item, otherwise return
     * a -1 to indicate failure.
     * 
     * @param username
     * @param password 
     * @param name
     * @param email
     * @return rowId or -1 if failed
     */
    public long createAccount(String username, String password, String name, String email){
    	ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ACCOUNT_USERNAME, username);
        initialValues.put(KEY_ACCOUNT_PASSWORD, password);
        initialValues.put(KEY_ACCOUNT_NAME, name);
        initialValues.put(KEY_ACCOUNT_EMAIL, email);
        
        return mMainDb.insert(DATABASE_ACCOUNT_TABLE, null, initialValues);
    }
    
    /**
     * Create a new category using the data provided. If the category is
     * successfully created return the new rowId for that category, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the category
     * @return rowId or -1 if failed
     */
    public long createCategory(String title, String accountId){
    	ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_CATEGORY_TITLE, title);
        initialValues.put(KEY_CATEGORY_ACCOUNTID, accountId);
        Log.d("ToDoApDb update Category", "mMainDb = " + mMainDb);
        return mMainDb.insert(DATABASE_CATEGORY_TABLE, null, initialValues);
    }
    
    /**
     * Create a new item using the data provided. If the item is
     * successfully created return the new rowId for that item, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the item
     * @param description the description of the item
     * @param location the location of the item
     * @param duedate the duedate of the item
     * @param categoryId the id of the category that the item is in
     * @return rowId or -1 if failed
     */
    public long createItem(String title, String description, String location, String duedate,
    		String accountId, String categoryId){
    	ContentValues initialValues = new ContentValues();
    	Log.d("ToDoAppDb createItem", "before putting values");
        initialValues.put(KEY_ITEM_TITLE, title);
        initialValues.put(KEY_ITEM_DESCRIPTION, description);
        initialValues.put(KEY_ITEM_LOCATION, location);
        initialValues.put(KEY_ITEM_DUEDATE, duedate);
        initialValues.put(KEY_ITEM_COMPLETE, "false");
        initialValues.put(KEY_ITEM_ACCOUNTID, accountId);
        initialValues.put(KEY_ITEM_CATEGORYID, categoryId);
        Log.d("ToDoAppDb createItem", "mMainDb = " + mMainDb);
        return mMainDb.insert(DATABASE_ITEM_TABLE, null, initialValues);
    }
    
    /**
     * Delete the category with the given rowId
     * 
     * @param rowId id of category to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteCategory(long rowId) {
        return mMainDb.delete(DATABASE_CATEGORY_TABLE, KEY_CATEGORY_ROWID + "=" + rowId, null) > 0;
    }
    
    /**
     * Delete the item with the given rowId
     * 
     * @param rowId id of item to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteItem(long rowId) {
        return mMainDb.delete(DATABASE_ITEM_TABLE, KEY_ITEM_ROWID + "=" + rowId, null) > 0;
    }
    
    /**
     * Return a Cursor over the list of all categories for the selected account.
     * 
     * @return Cursor over all categories for an account
     */
    public Cursor fetchAllCategories(String accountId) {

        return mMainDb.query(DATABASE_CATEGORY_TABLE, new String[] {KEY_CATEGORY_ROWID, KEY_CATEGORY_TITLE,
        		KEY_CATEGORY_ACCOUNTID}, KEY_CATEGORY_ACCOUNTID + "= ?", new String[] {accountId}, null, null, null);
    }
    
    /**
     * Return a Cursor over the list of all categories in the database
     * 
     * @return Cursor over all categories
     */
    public Cursor fetchAllCategories() {

        return mMainDb.query(DATABASE_CATEGORY_TABLE, new String[] {KEY_CATEGORY_ROWID, KEY_CATEGORY_TITLE, 
        		KEY_CATEGORY_ACCOUNTID}, null, null, null, null, null);
    }
    
    /**
     * Return a Cursor over the list of all items in the database
     * 
     * @return Cursor over all items
     */
    public Cursor fetchAllItems() {
    	Log.d("ToDoAppAd", "fetchAllItems() Begins");
        return mMainDb.query(DATABASE_ITEM_TABLE, new String[] {KEY_ITEM_ROWID, 
        		KEY_ITEM_TITLE, KEY_ITEM_DESCRIPTION, KEY_ITEM_LOCATION, KEY_ITEM_DUEDATE,
        		KEY_ITEM_COMPLETE, KEY_ITEM_ACCOUNTID, KEY_ITEM_CATEGORYID}, null , null, null, null, null);    
    }
    
    /**
     * Return a Cursor over the list of all items of a specific category in the database
     * 
     * @return Cursor over all items
     */
    public Cursor fetchAllItems(String accountId, String categoryId) {
    	Log.d("ToDoAppAd", "Beginning");
        return mMainDb.query(DATABASE_ITEM_TABLE, new String[] {KEY_ITEM_ROWID, 
        		KEY_ITEM_TITLE, KEY_ITEM_DESCRIPTION, KEY_ITEM_LOCATION, KEY_ITEM_DUEDATE,
        		KEY_ITEM_COMPLETE, KEY_ITEM_ACCOUNTID, KEY_ITEM_CATEGORYID}, KEY_ITEM_ACCOUNTID + "= '" + accountId + "' AND " + KEY_ITEM_CATEGORYID +
        		"= '" + categoryId + "'", null, null, null, null);
        
    }
    
    public Cursor fetchCompletedItems(String complete) {
    	Log.d("ToDoAppAd", "Beginning");
        return mMainDb.query(DATABASE_ITEM_TABLE, new String[] {KEY_ITEM_ROWID, 
        		KEY_ITEM_TITLE, KEY_ITEM_DESCRIPTION, KEY_ITEM_LOCATION, KEY_ITEM_DUEDATE,
        		KEY_ITEM_COMPLETE, KEY_ITEM_ACCOUNTID, KEY_ITEM_CATEGORYID}, KEY_ITEM_COMPLETE + 
        		"= ?", new String[] {complete}, null, null, null);
    }
    
    /**
     * Return a Cursor over the list of all accounts in the database
     * 
     * @return Cursor over all items
     */
    public Cursor fetchAccount(String username) {
    	Log.d("ToDoAppAd", "fetchAccount() Begins");
        return mMainDb.query(DATABASE_ACCOUNT_TABLE, new String[] {KEY_ACCOUNT_ROWID, 
        		KEY_ACCOUNT_USERNAME, KEY_ACCOUNT_PASSWORD, KEY_ACCOUNT_NAME, KEY_ACCOUNT_EMAIL},
        		KEY_ACCOUNT_USERNAME + "= ?", new String[] {username}, null, null, null);    
    }
    
    /**
     * Return a Cursor positioned at the category that matches the given rowId
     * 
     * @param rowId id of category to retrieve
     * @return Cursor positioned to matching category, if found
     * @throws SQLException if category could not be found/retrieved
     */
    public Cursor fetchCategory(long rowId) throws SQLException {

        Cursor mCursor =
        	
            mMainDb.query(true, DATABASE_CATEGORY_TABLE, new String[] {KEY_CATEGORY_ROWID,
                    KEY_CATEGORY_TITLE, KEY_CATEGORY_ACCOUNTID}, KEY_CATEGORY_ROWID + "=" + rowId, null,
                    null, null, null, null);
      
            mCursor.moveToFirst();
            Log.d("ToDoAppDb fetchCategory", "mCursor != null");
        return mCursor;
    }
    
    /**
     * Return a Cursor positioned at the item that matches the given rowId
     * 
     * @param rowId id of item to retrieve
     * @return Cursor positioned to matching item, if found
     * @throws SQLException if item could not be found/retrieved
     */
    public Cursor fetchItem(long rowId) throws SQLException {

        Cursor mCursor =

            mMainDb.query(true, DATABASE_ITEM_TABLE, new String[] {KEY_ITEM_ROWID,
                    KEY_ITEM_TITLE, KEY_ITEM_DESCRIPTION, KEY_ITEM_LOCATION, KEY_ITEM_DUEDATE,
                    KEY_ITEM_COMPLETE, KEY_ITEM_ACCOUNTID, KEY_ITEM_CATEGORYID}, 
                    KEY_ITEM_ROWID + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    
    /**
     * Update the category using the details provided. The category to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of category to update
     * @param title the title of the category
     * @return true if the category was successfully updated, false otherwise
     */
    public boolean updateCategory(long rowId, String title) {
        ContentValues args = new ContentValues();
        args.put(KEY_CATEGORY_TITLE, title);
        Log.d("ToDoApDb update Category", "mMainDb = " + mMainDb);
        return mMainDb.update(DATABASE_CATEGORY_TABLE, args, KEY_CATEGORY_ROWID + "=" + rowId, null) > 0;
    }
    
    /**
     * Update the item using the details provided. The item to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of item to update
     * @param title the title of the item
     * @param description the description of the item
     * @param location the location of the item
     * @param duedate the duedate of the item
     * @return true if the item was successfully updated, false otherwise
     */
    public boolean updateItem(long rowId, String title, String description, String location, String duedate) {
        ContentValues args = new ContentValues();
        args.put(KEY_ITEM_TITLE, title);
        args.put(KEY_ITEM_DESCRIPTION, description);
        args.put(KEY_ITEM_LOCATION, location);
        args.put(KEY_ITEM_DUEDATE, duedate);
        
        return mMainDb.update(DATABASE_ITEM_TABLE, args, KEY_ITEM_ROWID + "=" + rowId, null) > 0;
    }
    
    /**
     * Update the the complete status of an item. The item to be updated is
     * specified using the rowId, and it is reversed, then stored in the database.
     * @param rowId id of the item to update
     * @param complete current status of complete
     */
    public void updateComplete(long rowId, String complete)
    {
    	ContentValues args = new ContentValues();
    	if(complete.equals("false"))
    		args.put(KEY_ITEM_COMPLETE, "true");
    	else
    		args.put(KEY_ITEM_COMPLETE, "false");
    	Log.d("ToDoAppDb updateComplete", "complete = " + args.get(KEY_ITEM_COMPLETE));
    	
    	mMainDb.update(DATABASE_ITEM_TABLE, args, KEY_ITEM_ROWID + "=" + rowId, null);
    }
}
